
import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/foundation.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/api/HttpConfig.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/SpHelper.dart';

class HttpUtil {
  static const TAG="HttpLog";
  static bool _debug = kDebugMode;
  static const int maxLineLength= 500;
  static var instance;
  late Dio dio;
  late BaseOptions options;

  factory HttpUtil.of(){
    return _getInstance();
  }

  HttpUtil() {
    LogUtil.init(tag: HttpUtil.TAG,isDebug: true);
    dio = new Dio()
      ..options = BaseOptions(
          baseUrl: ApiHost.getIndex(ApiHost.API_IP_INDEX),
          connectTimeout: Duration(seconds: 10000),
          receiveTimeout: Duration(seconds: 10000))
      ..interceptors.add(HeaderInterceptor());
//      ..interceptors.add(LogInterceptor(responseBody: true, requestBody: true));
  }

  static HttpUtil _getInstance() {
    if (instance == null) {
      instance = new HttpUtil();
    }
    return instance;
  }
}

class HeaderInterceptor extends Interceptor {


  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
      log("请求：${options.baseUrl}${options.path}");
      log("参数：body==>${options.data.toString()}   params==>${options.queryParameters.toString()}");
      var token = SPHelper.getToken();
      if (token != null && token.length > 0) {
          options.headers.putIfAbsent('Authorization', () => "${SPHelper.getLoginInfo().tokenHead??'Bearer'}${token}");
      }
//    if (options.uri.path.indexOf('api/user/advice/Imgs') > 0 || options.uri.path.indexOf('api/user/uploadUserHeader') > 0) { // 上传图片
//      options.headers.putIfAbsent('Content-Type', () => 'multipart/form-data');
//      print('上传图片');
//    } else {
//    }
//    options.headers.putIfAbsent('Content-Type', () => 'application/json;charset=UTF-8');
      super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    super.onResponse(response, handler);
    log("结果: code=${response.statusCode}  message=${response.statusMessage}");
    log("结果: ==> ${response.data.toString()}");
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    super.onError(err, handler);
    log("错误结果: ==> ${err.error}");
  }

 static void log(dynamic obj){
    if(!HttpUtil._debug) return;
    String strLog=obj.toString();
    var len = strLog.length;
    if(len >50000){ //如果超过3000 不打印日志
       print("====日志太长了，本大爷懒得打印====");
       return;
    }
    StringBuffer sb=StringBuffer();
    if(len > HttpUtil.maxLineLength){
      var size=len~/ HttpUtil.maxLineLength ;
      for (int i = 0; i <= size; i++) {
         if(i==size){
           sb.writeln(strLog.substring(i*HttpUtil.maxLineLength,len));
         }else{
           sb.writeln(strLog.substring(i*HttpUtil.maxLineLength,(i+1)*HttpUtil.maxLineLength));
         }
      }
    }else{
      sb.write(strLog);
    }
    var str='''
      ${sb.toString()}
    ''';
    // LogUtil.e("${str}",tag: HttpUtil.TAG);
    print("${str}");
  }
}

